package com.wngbms.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo {

    public static void main(String[] args) {

        ReadWriteLock lock = new ReentrantReadWriteLock(false);

        Lock readLock = lock.readLock();
        Lock writeLock = lock.writeLock();

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            writeLock.lock();
            System.out.println("write locked2");

        }, "main-2").start();

        try {
            readLock.lock();
            System.out.println("read locked");

            writeLock.lock();
            System.out.println("write locked");

        } finally {
            readLock.unlock();
        }
    }

}
